<template>
  <div class="virtual-select" @click.stop="">
    <StyleCascader
      v-bind="$attrs"
      :selected-data="selectedData"
      @toggleMenu="toggleMenu"
      @deleteItem="deleteItem"
    ></StyleCascader>
    <div :id="renderId"></div>
  </div>
</template>

<script>
  import StyleCascader from './StyleCascader.vue';
  import { nanoid } from '@/utils';
  export default {
    name: 'VCascader',
    components: {
      StyleCascader,
    },
    inheritAttrs: false,
    props: {
      modelValue: {
        type: [Number, String, Array, Object], // 如果绑定值为数组，则为多选,否则为单选
        default: '',
      },
      options: {
        type: Array,
        default: () => [],
      },
    },
    emits: ['update:modelValue', 'change'],
    data() {
      return {
        renderId: nanoid(8),
        CommonCascader: this.$root.$refs['CommonCascader'],
      };
    },
    computed: {
      selectedData() {
        if (this.options.length === 0) return '';
        return this.modelValue.map((codeArr) => {
          let res = '';
          let tempItem = this.options;
          codeArr.forEach((code) => {
            const targetItem = tempItem.find((i) => i['code'] === code);
            res += `/${targetItem['name']}`;
            tempItem = targetItem['children'];
          });

          return res.slice(1);
        });
      },
    },
    methods: {
      toggleMenu() {
        this.CommonCascader.toggleMenu({
          renderId: this.renderId,
          curInstance: this,
          attrs: this.$attrs,

          curValue: this.modelValue,
          options: this.options,
        });
      },
      // 不要删除，给CommonSelect调用
      updateValue(val) {
        // this.$emit('update:modelValue',val)
        this.$emit('change', val);
      },
      deleteItem(idx) {
        // eslint-disable-next-line vue/no-mutating-props
        this.modelValue.splice(idx, 1);
        this.CommonCascader.forceUpdate();
        // this.$emit('change',this.modelValue)
      },
    },
  };
</script>

<style lang="scss" scoped>
  .virtual-select {
    position: relative;
    .common-select {
      :deep(.el-select) {
        position: absolute;
        left: 0;
        top: 0;
        z-index: -1;
        :deep(.el-input) {
          opacity: 1;
        }
      }
    }
  }
</style>
